<template>
    <div class="admin-permission-group-container">
      <!-- 筛选区和设置图标同一行 -->
      <div class="filter-bar">
        <div class="filter-container">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>

          <el-input
            v-model="searchQuery"
            placeholder="搜索角色名称"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
            style="width: 250px; margin-left: 10px;"
            size="small"
          >
          </el-input>

          <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">查询</el-button>
          <el-button size="small" @click="resetSearch">重置</el-button>
          <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleAdd">添加</el-button>
        </div>
        <div class="filter-setting-icon">
          <el-popover
            placement="bottom-end"
            width="220"
            trigger="click"
            v-model="showColumnSetting"
          >
            <div v-for="col in columns" :key="col.key">
              <el-checkbox v-model="col.visible">{{ col.label }}</el-checkbox>
            </div>
            <div style="text-align: right;">
              <el-button type="text" size="mini" @click="resetColumns">重置</el-button>
            </div>
            <i
              class="el-icon-setting"
              slot="reference"
              style="cursor: pointer; font-size: 20px; margin-left: 10px;"
            ></i>
          </el-popover>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%; margin-top: 20px;"
        border
        v-loading="loading"
      >
        <el-table-column v-if="getColumnVisible('index')"
          type="index"
          label="序号"
          width="80" align="center">
        </el-table-column>
        <el-table-column v-if="getColumnVisible('role_name')"
          prop="role_name"
          label="角色名称"
          min-width="150">
        </el-table-column>
        <el-table-column v-if="getColumnVisible('create_time')"
          prop="create_time"
          label="创建时间"
          width="180">
        </el-table-column>
        <el-table-column v-if="getColumnVisible('update_time')"
          prop="update_time"
          label="更新时间"
          width="180">
        </el-table-column>
        <el-table-column v-if="getColumnVisible('status')"
          prop="status"
          label="状态"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="getColumnVisible('operate')"
          label="操作"
          width="250" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
              size="small"
              @change="handleStatusChange(scope.row)"
            >
            </el-switch>
            <el-button type="text" size="small" style="margin-left: 10px;" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" style="margin-left: 10px; color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container" style="margin-top: 20px; text-align: right;">
        <PageCom :total="total" :pageSize="pageSize" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" :currentPage="currentPage"></PageCom>
      </div>

      <!-- 添加或编辑角色弹窗 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="500px"
        :before-close="handleClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="role_name">
            <el-input v-model="form.role_name" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="正常" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限" prop="permissions">
            <div class="permission-options">
              <el-checkbox v-model="selectAll">选择全部</el-checkbox>
              <el-checkbox v-model="expandAll">展开全部</el-checkbox>
            </div>
            <el-tree
              ref="permissionTree"
              :data="permissionTree"
              show-checkbox
              node-key="id"
              :props="{ children: 'children', label: 'name' }"
              :default-expand-all="expandAll"
              @check-change="handleCheckChange"
            ></el-tree>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import PageCom from '@/components/PageCom.vue';
  import { adminGroupList, updateGroupStatus, deleteGroup, addGroup, editGroup, getPermissionList } from '@/api/contract';
  
  export default {
    name: 'AdminPermissionGroupView',
    components: {
      PageCom,
    },
    data() {
      return {
        dateRange: null,
        searchQuery: '',
        tableData: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        loading: false,
        // 弹窗相关数据
        dialogVisible: false,
        dialogTitle: '添加角色',
        submitLoading: false,
        isEdit: false,
        permissionList: [], // 权限列表（扁平结构）
        permissionTree: [], // 权限树形结构
        checkedPermissions: [], // 选中的权限ID
        expandAll: false, // 展开全部
        selectAll: false, // 选择全部
        form: {
          id: '',
          role_name: '',
          status: 1,
          permissions: [] // 选中的权限ID数组
        },
        rules: {
          role_name: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
          // 权限验证将通过手动检查树组件的选中状态实现
          // permissions: [
          //   { type: 'array', required: true, message: '请选择权限', trigger: 'change' }
          // ]
        },
        // 字段显示控制配置
        columns: [
          { key: 'index', label: '序号', visible: true },
          { key: 'role_name', label: '角色名称', visible: true },
          { key: 'create_time', label: '创建时间', visible: true },
          { key: 'update_time', label: '修改时间', visible: true },
          { key: 'status', label: '状态', visible: true },
          { key: 'operate', label: '操作', visible: true }
        ],
        showColumnSetting: false,
      };
    },
    created() {
      this.fetchGroupList();
      this.fetchPermissionList();
    },
    watch: {
      expandAll(val) {
        this.setTreeExpansion(this.$refs.permissionTree.store.root, val);
      },
      selectAll(val) {
        this.$refs.permissionTree.setCheckedNodes(val ? this.permissionList : []);
        this.handleCheckChange();
      }
    },
    methods: {
      // 获取权限分组列表数据
      async fetchGroupList() {
        this.loading = true;
        try {
          const params = {
            page: this.currentPage,
            pageSize: this.pageSize,
            time: this.dateRange || [],
            keyword: this.searchQuery || '',
          };
          const response = await adminGroupList(params);
          // console.log('Admin Group List API Response:', response);
          if (response.data.code === 200) {
            this.tableData = response.data.data.data || [];
            this.total = response.data.data.total || 0;

            if (this.tableData.length === 0 && this.total > 0) {
              // 如果当前页没有数据但总数大于0，尝试回到上一页或第一页
               if (this.currentPage > 1) {
                   this.currentPage--;
                   this.fetchGroupList(); // 重新获取数据
               } else {
                   this.$message.warning('当前筛选条件下暂无数据');
               }
            } else if(this.tableData.length === 0 && this.total === 0){
                 this.$message.warning('暂无数据');
            }

          } else {
            this.$message.error(response.data.message || '获取数据失败');
            this.tableData = [];
            this.total = 0;
          }
        } catch (error) {
          console.error('获取权限分组列表失败:', error);
          this.$message.error('获取数据失败，请稍后重试');
          this.tableData = [];
          this.total = 0;
        } finally {
          this.loading = false;
        }
      },
      // 每页条数改变
      handleSizeChange(val) {
        this.pageSize = val;
        this.currentPage = 1; // 切换每页条数时，重置到第一页
        this.fetchGroupList();
      },
      // 页码改变
      handleCurrentChange(val) {
        this.currentPage = val;
        this.fetchGroupList();
      },
      handleSearch() {
        this.currentPage = 1; // 查询时重置到第一页
        this.fetchGroupList();
      },
      resetSearch() {
        this.dateRange = null;
        this.searchQuery = '';
        this.currentPage = 1;
        this.pageSize = 10; // 重置每页条数到默认值
        this.fetchGroupList();
      },
      handleStatusChange(row) {
        this.$confirm(`确认要${row.status === 1 ? '启用' : '禁用'}该角色吗?同时该角色组的所有角色状态都被修改`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const response = await updateGroupStatus(row.id);
            if (response.data.code === 200) {
              this.$message.success('状态修改成功');
              this.fetchGroupList();
            } else {
              this.$message.error(response.data.message || '状态修改失败');
              // 恢复开关状态
              row.status = row.status === 1 ? 0 : 1;
            }
          } catch (error) {
            console.error('状态修改失败:', error);
            this.$message.error('状态修改失败，请稍后重试');
            // 恢复开关状态
            row.status = row.status === 1 ? 0 : 1;
          }
        }).catch(() => {
          // 取消操作，恢复开关状态
          row.status = row.status === 1 ? 0 : 1;
          this.$message.info('已取消操作');
        });
      },
      handleEdit(row) {
        this.isEdit = true;
        this.dialogTitle = '编辑角色';
        // 解析 permissions 字符串为数组
        const permissionsArray = row.permissions ? JSON.parse(row.permissions) : [];
        this.form = {
          id: row.id,
          role_name: row.role_name,
          status: row.status,
          permissions: permissionsArray // 设置已选中的权限ID数组
        };
        this.dialogVisible = true;
        // 设置树形组件的选中状态
        this.$nextTick(() => {
          if (this.$refs.permissionTree && this.form.permissions) {
             // el-tree 的 setCheckedKeys 接收一个包含节点 key 的数组
             this.$refs.permissionTree.setCheckedKeys(this.form.permissions);
             // 这里不需要调用 handleCheckChange()，setCheckedKeys 会触发 check-change 事件
             // this.handleCheckChange(); // 同步选择全部/展开全部状态
          }
        });
      },
      handleDelete(row) {
        this.$confirm('确认要删除该角色吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const response = await deleteGroup(row.id);
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.fetchGroupList();
            } else {
              this.$message.error(response.data.message || '删除失败');
            }
          } catch (error) {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          }
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },
      handleAdd() {
        this.isEdit = false;
        this.dialogTitle = '添加角色';
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.resetForm();
        });
      },
      resetForm() {
        this.form = {
          id: '',
          role_name: '',
          status: 1,
          permissions: []
        };
        this.checkedPermissions = [];
        this.expandAll = false;
        this.selectAll = false;
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
        if (this.$refs.permissionTree) {
          this.$refs.permissionTree.setCheckedKeys([]);
        }
      },
      handleCheckChange() {
        // 获取所有选中和半选中的节点ID
        const checkedNodes = this.$refs.permissionTree.getCheckedNodes();
        const halfCheckedNodes = this.$refs.permissionTree.getHalfCheckedNodes();
        const checkedKeys = checkedNodes.map(node => node.id);
        const halfCheckedKeys = halfCheckedNodes.map(node => node.id);
        
        // 将选中和半选中的节点ID合并到form.permissions中
        this.form.permissions = [...checkedKeys, ...halfCheckedKeys];

        // 更新选择全部/展开全部的状态
        this.selectAll = checkedNodes.length === this.permissionList.length;
      },
      submitForm() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            // 检查是否选择了权限
            if (this.form.permissions.length === 0) {
              this.$message.warning('请至少选择一个权限');
              return;
            }
            this.submitLoading = true;
            try {
              const response = this.isEdit ? 
                await editGroup(this.form) : 
                await addGroup(this.form);
              
              if (response.data.code === 200) {
                this.$message.success(this.isEdit ? '更新成功' : '添加成功');
                this.dialogVisible = false;
                this.fetchGroupList();
              } else {
                this.$message.error(response.data.message || (this.isEdit ? '更新失败' : '添加失败'));
              }
            } catch (error) {
              console.error(this.isEdit ? '更新失败:' : '添加失败:', error);
              this.$message.error(this.isEdit ? '更新失败，请稍后重试' : '添加失败，请稍后重试');
            } finally {
              this.submitLoading = false;
            }
          }
        });
      },
      handleClose() {
        this.dialogVisible = false;
        this.resetForm();
      },
      // 将扁平结构的权限列表转换为树形结构
      convertToTree(list, parentId = 0) {
        const tree = [];
        list.forEach(item => {
          if (item.parentId === parentId) {
            const children = this.convertToTree(list, item.id);
            if (children.length) {
              item.children = children;
              // 根据listorder对子节点排序
              item.children.sort((a, b) => a.listorder - b.listorder);
            }
            tree.push(item);
          }
        });
        // 根据listorder对顶层节点排序
        tree.sort((a, b) => a.listorder - b.listorder);
        return tree;
      },
      // 设置树节点的展开状态
      setTreeExpansion(node, expand) {
        node.expanded = expand;
        if (node.childNodes) {
          node.childNodes.forEach(childNode => {
            this.setTreeExpansion(childNode, expand);
          });
        }
      },
      // 获取权限列表
      async fetchPermissionList() {
        try {
          const response = await getPermissionList();
          // console.log('Permission List API Response:', response);
          if (response.data.code === 200) {
            this.permissionList = response.data.data || [];
            this.permissionTree = this.convertToTree(this.permissionList);
          } else {
            this.$message.error(response.data.message || '获取权限列表失败');
          }
        } catch (error) {
          console.error('获取权限列表失败:', error);
          this.$message.error('获取权限列表失败，请稍后重试');
        }
      },
      getColumnVisible(key) {
        const col = this.columns.find(c => c.key === key);
        return col ? col.visible : false;
      },
      resetColumns() {
        this.columns.forEach(col => col.visible = true);
      }
    }
  };
  </script>
  
  <style scoped>
  .admin-permission-group-container {
    padding: 20px;
    background-color: #fff;
    min-height: calc(100vh - 60px - 20px);
    box-sizing: border-box;
  }
  
  .filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  .filter-container {
    display: flex;
    align-items: center;
  }
  .filter-setting-icon {
    display: flex;
    align-items: center;
    height: 32px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  ::v-deep .el-table {
    border: 1px solid #EBEEF5;
  }
  
  ::v-deep .el-table th {
    background-color: #f5f7fa !important;
    color: #606266;
  }
  
  ::v-deep .el-table td, ::v-deep .el-table th {
    border-bottom: 1px solid #EBEEF5;
    border-right: 1px solid #EBEEF5;
  }
  
  ::v-deep .el-table th:last-child,
  ::v-deep .el-table td:last-child {
    border-right: none;
  }
  
  ::v-deep .el-table::after, ::v-deep .el-table::before {
    background-color: transparent;
  }

  .el-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  .el-checkbox {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .permission-options {
    margin-bottom: 10px;
  }

  .el-tree {
    border: 1px solid #DCDFE6;
    padding: 10px;
    border-radius: 4px;
  }
  ::v-deep .el-input__inner {
  background-color: white !important;
}
  </style>
  